//
//  PageContenView.swift
//  JFDouYu
//
//  Created by xujf on 2017/11/14.
//  Copyright © 2017年 XuJF. All rights reserved.
//

import UIKit

protocol PageContentViewDelegate:class {
    func pageContentView(pageContetenView : PageContentView, progress : CGFloat, sourceIndex:Int, targetIndex:Int)
}
private let CollectionCellId = "CollectionCellId"
class PageContentView: UIView {
    fileprivate var childVcs : [UIViewController]
    fileprivate weak var parentViewController : UIViewController?
    fileprivate var startOffSetX : CGFloat = 0.0
     weak var delegate : PageContentViewDelegate?
    fileprivate var isForbidScrollViewDelegate : Bool = false
    fileprivate lazy var collectionView : UICollectionView = {[weak self] in
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = (self?.bounds.size)!
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.isPagingEnabled = true
        collectionView.bounces = false
        collectionView.dataSource = self
        collectionView.scrollsToTop = false
        collectionView.delegate = self// as ? UICollectionViewDelegate
//        UICollectionViewCell.self 拿到类型
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: CollectionCellId)
        return collectionView
    }()
//    let layout = UICollectionViewFlowLayout()
////    layout.item
//    layout.itemSize = (self.bounds.size)
    
    
//    let collectionView = UICollectionView(frame: <#T##CGRect#>, collectionViewLayout: <#T##UICollectionViewLayout#>)
    init(frame: CGRect, childVcs : [UIViewController], parentViewController :UIViewController?) {
        self.childVcs = childVcs
        self.parentViewController = parentViewController
        super.init(frame:frame)
        setupUI()
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK:- 设置UI界面
extension PageContentView{
    fileprivate func setupUI(){
        //将所有的自控制器添加到副控制器中
        for childVc in childVcs{
            parentViewController?.addChildViewController(childVc)
        }
        addSubview(collectionView)
        collectionView.frame = bounds
    }
}
//MARK:-遵守UICollectionViewDataSource
extension PageContentView :UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return childVcs.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionCellId, for: indexPath)
       //给cell 设置内容
        for view in cell.contentView.subviews {
            view.removeFromSuperview()
        }
        let childVc = childVcs[indexPath.item]
        childVc.view.frame = cell.contentView.bounds
        childVc.view.backgroundColor = UIColor.randomColor()
        cell.contentView.addSubview(childVc.view)
        return cell
    }
    
}
//MARK:-遵守协议
extension PageContentView :UICollectionViewDelegate{
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        startOffSetX = scrollView.contentOffset.x
        isForbidScrollViewDelegate = false
        
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if isForbidScrollViewDelegate {return}
        print("%f",scrollView.contentOffset.x)
        //1.定义获取需要的数据
        var progress : CGFloat = 0
        var sourceIndex : Int = 0
        var targetIndex : Int = 0
        
        //2判断是左滑还是右滑
        let currentOffsetX = scrollView.contentOffset.x
        let scrollViewW = scrollView.bounds.width
        
        if currentOffsetX > startOffSetX { // 左滑
            // 1.计算progress
            progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
            
            // 2.计算sourceIndex
            sourceIndex = Int(currentOffsetX / scrollViewW)
            
            // 3.计算targetIndex
            targetIndex = sourceIndex + 1
            if targetIndex >= childVcs.count {
                targetIndex = childVcs.count - 1
            }
            
            // 4.如果完全划过去
            if currentOffsetX - startOffSetX == scrollViewW {
                progress = 1
                targetIndex = sourceIndex
            }
        } else { // 右滑
            // 1.计算progress
            progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
            
            // 2.计算targetIndex
            targetIndex = Int(currentOffsetX / scrollViewW)
            
            // 3.计算sourceIndex
            sourceIndex = targetIndex + 1
            if sourceIndex >= childVcs.count {
                sourceIndex = childVcs.count - 1
            }
        }
        
        // 3.将progress/sourceIndex/targetIndex传递给titleView
        delegate?.pageContentView(pageContetenView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
        print("sdsdsdds\(progress)","\(targetIndex)","\(sourceIndex)")
    }
}

extension PageContentView{
    func setCurrentIndex(currentIndex:Int) {
        // 1.记录需要进制执行代理方法
        isForbidScrollViewDelegate = true
        
        let offSex  = CGFloat(currentIndex) * collectionView.frame.width
        
        collectionView.setContentOffset(CGPoint(x: offSex, y: 0), animated: false)
    }
}
